package marker.micro.gateway.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import com.netflix.zuul.context.RequestContext;

public class AccessFilter extends AbstractZuulFilter {

    @Override
    public boolean shouldFilter() {
	return true;
    }

    @Override
    public Object run() {
	RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        logger.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));

        Object accessToken = request.getParameter("accessToken");
        if(accessToken == null) {
            logger.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpServletResponse.SC_BAD_REQUEST);
            ctx.setResponseBody("The times of usage is limited");
            return null;
        }
        logger.info("access token ok");
        return null;
    }

    @Override
    public String filterType() {
	return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
	return 0;
    }

}
